package com.example.elm.HomeAndSearch

import android.content.Context
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.example.elm.HomeAndSearch.ui.theme.ElmTheme
import com.example.elm.Public.MyApplication
import com.example.elm.Public.StoreInfo
import com.example.elm.R
import com.example.elm.databinding.ActivitySearchBinding
import com.example.elm.StoreAndGoods.StoreActivity
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.OkHttpClient
import okhttp3.Request
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import java.io.StringReader
import java.net.URLEncoder
import kotlin.concurrent.thread

class SearchActivity : ComponentActivity() {
    private var storeList = ArrayList<StoreInfo>()
    private var searchList = ArrayList<String>()
    private val server_ip = MyApplication.serverIp // 服务器地址，这是手机热点的
    private var n:Int = 1
    private lateinit var  binding: ActivitySearchBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivitySearchBinding.inflate(layoutInflater)
        setContentView(binding.root)

    // 搜索记录部分
        // 从文件中读取数据
        readFromFile()
        // 初始化 searchadapter
        val searchAdapter = SearchAdapter(searchList)
        binding.historySearchRV.adapter = searchAdapter
        //搜索记录recyclerView布局管理器, 设置 RecyclerView 的布局管理器位水平滚动
        binding.historySearchRV.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, true)
        searchAdapter.notifyDataSetChanged()

        // 接收从 HomeMainFragment 传递过来的数据
        var searchData = intent.getStringExtra("search_data")

        // 将数据填充到UI中
        while (n == 1){
            binding.etSearch.setText(searchData)
            n = 0
        }

        // 搜索按钮
        binding.btnSearch.setOnClickListener{
            searchData = binding.etSearch.text.toString()
            SearchByName(searchData)
            searchList.add(searchData.toString())
            if (searchList.size > 8) {
                searchList.removeAt(0)
            }
            savaToFile()
            searchAdapter.notifyDataSetChanged()
        }
        // 清除历史记录按钮
        binding.btnFlush.setOnClickListener {
            searchList.clear()
            savaToFile()
            searchAdapter.notifyDataSetChanged()
        }

        // 搜索结果recyclerView布局管理器
        val layoutManager = LinearLayoutManager(this)
        binding.homeRecyclerView.layoutManager = layoutManager
        val adapter = StoreAdapter(storeList)
        binding.homeRecyclerView.adapter = adapter
        binding.homeRecyclerView.addItemDecoration(SpaceItemDecoration(15))// 设置recyclerView子项的底部间距,10px

        // 设置按钮点击事件，保存修改后的数据并返回
        binding.btnBack.setOnClickListener {
            finish()
        }
    }

    private class SpaceItemDecoration(private val space: Int) : RecyclerView.ItemDecoration() {
        override fun getItemOffsets(
            outRect: Rect,
            view: View,
            parent: RecyclerView,
            state: RecyclerView.State
        ) {
            outRect.bottom = space  // 设置recyclerView子项的底部间距
        }
    }


    private class SearchAdapter(val SearchList:ArrayList<String>) : RecyclerView.Adapter<SearchAdapter.SearchViewHolder>() {
        class SearchViewHolder(itemView: View) : ViewHolder(itemView) {
            val tvSearch:TextView = itemView.findViewById(R.id.tvSearch)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SearchViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(
                R.layout.search_elem, parent, false
            )
            return SearchViewHolder(view)
        }

        override fun onBindViewHolder(holder: SearchViewHolder, position: Int) {
            val searchData = SearchList[position]
            holder.tvSearch.text = "${searchData}\t\t"
        }

        override fun getItemCount(): Int {
            return SearchList.size
        }
    }

    // 将搜索记录保存到文件中
    private fun savaToFile() {
        val gson = Gson()
        val jsonString = gson.toJson(searchList)
        val editor = getSharedPreferences("history", Context.MODE_PRIVATE).edit()
        editor.putString("searchList", jsonString)
        editor.apply()
    }
    // 从文件读取记录
    private fun readFromFile() {
        val hand = getSharedPreferences("history", Context.MODE_PRIVATE)
        val jsonString = hand.getString("searchList", "")
        val gson = Gson()
        if (!jsonString.isNullOrEmpty()) {
            val type = object : TypeToken<ArrayList<String>>() {}.type
            searchList = gson.fromJson(jsonString, type)
        }
    }


    // 搜索结果的recyclerView适配器
    private class StoreAdapter(val StoreList: ArrayList<StoreInfo>) : RecyclerView.Adapter<ViewHolder>() {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(
                R.layout.home_store_elem, parent, false
            )
            StoreViewHolder(view).itemView.setOnClickListener{
                val intent = Intent(parent.context, StoreActivity::class.java)
                val StoreName = view.findViewById<TextView>(R.id.tvName).text.toString()
                intent.putExtra("store_data", StoreName)
                parent.context.startActivity(intent)
            }
            return StoreViewHolder(view)
        }
        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val storeInfo = StoreList[position]
            (holder as StoreViewHolder).bind(storeInfo)
        }

        override fun getItemCount(): Int {
            return StoreList.size
        }
        // Store ViewHolder
        class StoreViewHolder(itemView: View) : ViewHolder(itemView) {
            val image: ImageView = itemView.findViewById(R.id.imageView)
            val name: TextView = itemView.findViewById(R.id.tvName)
            val delivertTime: TextView = itemView.findViewById(R.id.tvDeliveryTime)
            val distance: TextView = itemView.findViewById(R.id.tvDistance)
            val rating: TextView = itemView.findViewById(R.id.tvRating)
            val sales: TextView = itemView.findViewById(R.id.tvSales)
            val minPrice: TextView = itemView.findViewById(R.id.tvMinPrice)
            val deliveryCost: TextView = itemView.findViewById(R.id.tvDeliveryCost)
            val recommend: TextView = itemView.findViewById(R.id.tvRecommend)
            val campusSend: TextView = itemView.findViewById(R.id.tvCampusSend)

            fun bind(storeInfo: StoreInfo) {
                val imageResId = itemView.context.resources.getIdentifier(
                    storeInfo.image, "drawable", itemView.context.packageName
                )
                if (imageResId != 0) {
                    image.setImageResource(imageResId)
                } else {
                    image.setImageResource(R.drawable.cqxm)
                }
                name.text = storeInfo.name
                delivertTime.text = storeInfo.deliveryTime
                distance.text = storeInfo.distance
                rating.text = "${storeInfo.rating}分"
                sales.text = "月售${storeInfo.sales}+"
                minPrice.text = "起送￥${storeInfo.minPrice}"
                deliveryCost.text = storeInfo.deliveryCost
                recommend.text = storeInfo.recommend
                campusSend.text = if (storeInfo.campusSend > 0) "校园送" else ""
            }
        }

    }

    // 通过xml读取
    fun SearchByName(searchData:String?){
        val homeStore_all = "http://$server_ip:8080/HomeAndSearch/search_by_name.jsp?searchData=${URLEncoder.encode(searchData, "UTF-8")}"
        thread {
            try{
                val client = OkHttpClient()
                val request: Request = Request.Builder()
                    .url(homeStore_all)
                    .build()
                val response = client.newCall(request).execute()
                val responseData = response.body?.string()
                if (!responseData.isNullOrEmpty()) {
                    parseXml(responseData.toString().trim())
                } else {
                    runOnUiThread {
                        Toast.makeText(this, "没有数据", Toast.LENGTH_LONG).show()
                    }
                }
            }
            catch (e: Exception){
                e.printStackTrace()
            }
        }
    }

    // 解析xml
    fun parseXml(xmlStr: String): String{
        try {
            val factory = XmlPullParserFactory.newInstance()
            val xmlPullPaser = factory.newPullParser()
            // 设置xml解析器的输入
            xmlPullPaser.setInput(StringReader(xmlStr))
            storeList.clear()
            var eventType = xmlPullPaser.eventType//  事件类型
            var idStr = ""
            var image = ""
            var name = ""
            var deliveryTime = ""
            var distance = ""
            var ratingStr = ""
            var salesStr = ""
            var minPriceStr = ""
            var deliveryCost = ""
            var recommend = ""
            var campusSendStr = ""
            while(eventType != XmlPullParser.END_DOCUMENT){
                val nodeName = xmlPullPaser.name
                // builder.append("${nodeName}--")
                when(eventType) {
                    // 标签开始
                    XmlPullParser.START_TAG -> {
                        when (nodeName) {
                            "id" -> idStr = xmlPullPaser.nextText()
                            "image" -> image = xmlPullPaser.nextText()
                            "name" -> name = xmlPullPaser.nextText()
                            "deliveryTime" -> deliveryTime = xmlPullPaser.nextText()
                            "distance" -> distance  = xmlPullPaser.nextText()
                            "rating" -> ratingStr = xmlPullPaser.nextText()
                            "sales" -> salesStr = xmlPullPaser.nextText()
                            "minPrice" -> minPriceStr = xmlPullPaser.nextText()
                            "deliveryCost" -> deliveryCost = xmlPullPaser.nextText()
                            "recommend" -> recommend = xmlPullPaser.nextText()
                            "campusSend" -> campusSendStr = xmlPullPaser.nextText()
                        }
                    }
                    // 标签结束
                    XmlPullParser.END_TAG -> {
                        if ("Store" == nodeName) {
                            storeList.add(
                                StoreInfo(
                                    idStr.toIntOrNull() ?: 0,
                                    image,
                                    name,
                                    deliveryTime,
                                    distance,
                                    ratingStr.toDoubleOrNull() ?: 0.0,
                                    salesStr.toIntOrNull() ?: 0,
                                    minPriceStr.toIntOrNull() ?: 0,
                                    deliveryCost,
                                    recommend,
                                    campusSendStr.toIntOrNull() ?: 0
                                )
                            )
                        }
                    }
                }
                eventType = xmlPullPaser.next() //  读取下一个，进行遍历
            }
            runOnUiThread{
                binding.homeRecyclerView.adapter?.notifyDataSetChanged()
            }
        }
        catch (e: Exception){
            e.printStackTrace()
        }
        return ""
    }
}


@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
    Text(
        text = "Hello $name!",
        modifier = modifier
    )
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    ElmTheme {
        Greeting("Android")
    }
}